<?php

namespace app\admin\model\member;

use app\api\controller\Wxpay;
use app\api\controller\Wxpaynew;
use think\Model;
use traits\model\SoftDelete;

class Payorder extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'payorder';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 定义时间戳字段的自动转换
    protected $dateFormat = 'Y-m-d H:i:s';

    // 定义获取器，将时间戳字段自动转换为特定格式
    public function getCreateTimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }
//    protected $type = [
//        'createtime'  =>     'datetime:Y-m-d H:i:s'
//    ];

    // 追加属性
    protected $append = [
        'status_text',
        'pay_time_text'
    ];
    

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public static function createOrder($data = [])
    {
        try {
            $order_info = [
                'no' => self::getNewOrderId(2),
                'user_id' => $data['user_id'],
                'num' => $data['num'],
                'price' => $data['price'],
                'remark' => "扫描".$data['price']."元--".$data['num']."次",
            ];
            $order = self::create($order_info);
            if (!$order) {
                throw new Exception('订单生成失败!');
            }
            return $order;
        } catch (Exception $e) {
            return self::setErrorInfo($e->getMessage());
        }
    }
//订单列表
    public static function lst($user_id, $params)
    {
        $page = !empty($params['page']) ? $params['page'] : 1;
        $limit = !empty($params['limit']) ? $params['limit'] : 10;
        $list = self::order('createtime desc')
            ->where('user_id', $user_id)
            ->page((int)$page, (int)$limit)
            ->select();

        return $list;
    }
    //微信小程序支付
    public static function pay($order)
    {
        // $wx = new Wxpay();
        // return $wx->getPayUrl($order);
        $wx = new Wxpaynew();
        $result =  $wx->getPayUrl($order);
        if (is_array($result)) {
            return  $wx->getPaysign($result['prepay_id']);
        }
        return $result;
    }

    /**
     * 生成订单唯一id
     * @return string
     */
    public static function getNewOrderId($type)
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        $no = $type . $msectime . mt_rand(10000, 99999);
        if (self::where('no', $no)->find()) {
            $no = $type . $msectime . mt_rand(10000, 99999);
        }
        return $no;
    }


    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
